<?php

/**
 * Created by PhpStorm.
 * User: PuLinGao
 * Date: 2014/11/04
 * Time: 01:00
 * 问卷管理,主要为问卷基本信息，问卷题目管理
 */
class QuestionController extends AdminController {
	/*
	 * 问卷列表 
	 */

	public function actionList() {

		$p = (int) $this->get('p', 1);
		$project_id = (int) $this->get('project_id');

		$params = array();
		$params['question_name'] = $this->request('question_name', '');
		$params['identifier'] = $this->request('identifier', '');
		$params['status'] = $this->request('status', '');
		$params['export'] = $this->request('export', '');

		$criteria = new CDbCriteria();
		//指定项目的问卷
		if ($this->project_id != -1) {
			$criteria->addInCondition('project_id', explode(',', $this->project_id));
		}
		if ($project_id) {
			$criteria->addCondition('project_id=' . $project_id);
		}

		$statusWhere = ($params['status'] === '') ? 'status in (1,2,100)' : 'status=' . $params['status'];
		$criteria->addCondition($statusWhere);
		if ($params['question_name']) {
			$criteria->addSearchCondition('question_name', $params['question_name']);
		}
		if ($params['identifier']) {
			$criteria->addSearchCondition('identifier', $params['identifier']);
		}

		$count = QuestionBase::model()->count($criteria);

		$criteria->limit = $this->limit;
		$criteria->offset = ($p - 1) * $this->limit;
		$criteria->order = 'create_time DESC';
		$data = QuestionBase::model()->findAll($criteria);

		if ($data) {
			//项目名称
			$project = new Project();
			foreach ($data as $key => $val) {
				$project_info = $project->findByPk($val['project_id'])->attributes;
				$data[$key]['project_name'] = $project_info['project_name'];
			}
		}
		$page = new Page($count, $this->limit);

		$this->smarty->assign('status', QuestionBase::questionBaseStatus());
		$this->smarty->assign('params', $params);
		$this->smarty->assign('page', $page->style1());
		$this->smarty->assign('list', $data);
		$this->smarty->assign('project_id', $project_id);
		$this->smarty->display('question/list.tpl');
	}

	/**
	 * 添加问卷
	 */
	public function actionAdd() {
		$project_id = (int) $this->get('project_id');
		$criteria = new CDbCriteria();
		//某个项目权限
		if ($this->project_id != -1) {
                    $criteria->condition = 'project_id in (' . $this->project_id . ')';
		}
		$criteria->addInCondition('status', array(-1,1));
		$project = Project::model()->findAll($criteria);
		$this->smarty->assign('project', $project);
		$this->smarty->assign('project_id', $project_id);
		$this->smarty->display('question/add.tpl');
	}

	/**
	 * 处理添加
	 * 添加问卷，同时导入问卷的网点
	 */
	public function actionDoAdd() {
		$questionBaseModel = new QuestionBase();
		$identifier = $this->post('identifier');
		$project_id = $this->post('project_id');
                $show_score = $this->post('show_score');

		# 检验重复值
		$isRepeat = $questionBaseModel->find('identifier=:identifier and status!=0', array(':identifier' => $identifier));
		if ($isRepeat) {
			$this->jump('已经存在该问卷编号');
		}

		# 检测bank_id
		$projects = Project::model()->find('project_id=:project_id and status!=0', array(':project_id' => $project_id));
		$bank_id = $projects->bank_id;
		if (!$bank_id) {
			$this->jump('项目无所属银行，请先修改项目！', '/webadmin/project	/list');
		}

		//先处理网点excel，便于提示上传者
		$modelQuesNetworkImport = new QuestionNetworkImportModel();
		$upload = new Uploader();
		$config = array(
			'new_name' => $project_id . '_question_network',
			'allow_ext' => 'xls,xlsx',
			'save_path' => dirname(Yii::app()->basePath) . '/assets/question_network/',
			'allow_max_size' => 8000000
		);
		$upload->init($config);
		if ($upload->check()) {
			$uploadFilePath = $upload->up();

			//解析网点excel的内容
			try {
				$this->enablePHPExcel();
				$questionImport = new QuestionExcel();
				$type = explode('.', $uploadFilePath);
				$message = $questionImport->questionNetworkImport($uploadFilePath, $type[1]);
			} catch (Exception $exc) {
				$error[] = $exc->getMessage();
			}
			if (!empty($error)) {
				$this->jump(join(' | ', $error));
			}

			//处理解析数据(提示)
			$modelQuesNetworkImport->formatExcelData($message['msg'], $bank_id);
			$formatError = $modelQuesNetworkImport->getError();
			if (!empty($formatError)) {
				$this->smarty->assign('backurl', '/webadmin/question/add?project_id=' . $project_id);
				$this->smarty->assign('error', $formatError);
				$this->smarty->display('question/import_error.tpl');
				exit;
			}
		}

		# 处理添加问卷等入库操作
		$questionBaseModel->identifier = $identifier;
		$questionBaseModel->question_name = $this->post('question_name');
		$questionBaseModel->project_id = $project_id;
                $questionBaseModel->show_score = intval($show_score);
		$questionBaseModel->create_time = time();
		$questionBaseModel->update_time = time();
		$questionBaseModel->status = QuestionBase::QUESTION_DRAFT;
		$questionBaseModel->user_id = $this->user_id;
		$res = $questionBaseModel->save();
		$questionId = $questionBaseModel->attributes['question_id'];
		if ($res) {
			$status = $modelQuesNetworkImport->saveExcelData($project_id, $questionId, $bank_id);
                        //更新项目的问卷数量,默认草稿状态不加入项目数量
                        //$project = Project::model()->findByPk($project_id);
                        //$project->saveCounters(array('question_num' => 1));
			$this->jump('保存成功', '/webadmin/question/list');
		} else {
			$this->jump('保存失败');
		}
	}

	/**
	 * 修改
	 */
	public function actionEdit() {
		$questionId = (int) $this->get('question_id');
		$questionBase = new QuestionBase();
		$info = $questionBase->findByPk($questionId);
		$criteria = new CDbCriteria();
		//某个项目权限
		if ($this->project_id != -1) {
			$criteria->condition = 'project_id in (' . $this->project_id . ')';
		}
		$project = Project::model()->findAll($criteria);
		$this->smarty->assign('project', $project);
		$this->smarty->assign('info', $info);
		$this->smarty->assign('question_id', $questionId);
		$this->smarty->assign('project_id', $info['project_id']);
		$this->smarty->display('question/add.tpl');
	}

	/**
	 * 处理修改
	 */
	public function actionDoEdit() {
		$questionId = $this->post('question_id');
		$project_id = $this->post('project_id');
                $show_score = $this->post('show_score');
		# 检测bank_id
		$projects = Project::model()->find('project_id=:project_id and status!=0', array(':project_id' => $project_id));
		$bank_id = $projects->bank_id;
		if (!$bank_id) {
			$this->jump('项目无所属银行，请先修改项目！', '/webadmin/project/list');
		}

		//先处理网点excel，便于提示上传者
		$upload = new Uploader();
		$modelQuesNetworkImport = new QuestionNetworkImportModel();
		$config = array(
			'new_name' => $questionId,
			'allow_ext' => 'xls,xlsx',
			'save_path' => dirname(Yii::app()->basePath) . '/assets/question_network/',
			'allow_max_size' => 8000000
		);
		$upload->init($config);
		if ($upload->check()) {
			$uploadFilePath = $upload->up();
			
			//存在上传文件，解析网点excel的内容
			try {
				$this->enablePHPExcel();
				$questionImport = new QuestionExcel();
				$type = explode('.', $uploadFilePath);
				$message = $questionImport->questionNetworkImport($uploadFilePath, $type[1]);
			} catch (Exception $exc) {
				$error[] = $exc->getMessage();
			}
			if (!empty($error)) {
				$this->jump(join(' | ', $error));
			}
			
			//处理解析数据(提示)
			$modelQuesNetworkImport->formatExcelData($message['msg'], $bank_id);
			$formatError = $modelQuesNetworkImport->getError();
			if (!empty($formatError)) {
				$this->smarty->assign('backurl', '/webadmin/question/edit?question_id=' . $questionId);
				$this->smarty->assign('error', $formatError);
				$this->smarty->display('question/import_error.tpl');
				exit;
			}
		}

		# 获取post值
		$data['identifier'] = $this->post('identifier');
		$data['question_name'] = $this->post('question_name');
		$data['project_id'] = $this->post('project_id');
                $data['show_score'] = intval($show_score);
		$data['update_time'] = time();
		//$data['status'] = QuestionBase::QUESTION_DRAFT;

		$objQuestionBase = new QuestionBase();
		$res = $objQuestionBase->updateByPk($questionId, $data);
		if ($res) {
			$status = $modelQuesNetworkImport->saveExcelData($data['project_id'], $questionId, $bank_id);
			$this->jump('修改成功', '/webadmin/question/list');
		} else {
			$this->jump('修改失败');
		}
	}

	/**
	 * 删除
	 */
	public function actionDelete() {
		$questionId = $this->post('question_id');

		$objQuestionBase = new QuestionBase();
		$info = $objQuestionBase->findByPk($questionId);
		if ($info->status == QuestionBase::QUESTION_RELEASE) {
                    $this->_ajax(array('status' => 0,'note' => '问卷处于发布状态，不能删除！'));
		}
                if ($info->status == QuestionBase::QUESTION_COMPLETE) {
                    $this->_ajax(array('status' => 0,'note' => '问卷已完成，不能删除！'));
                }
                $project_id = $info['project_id'];
		$data['status'] = QuestionBase::QUESTION_DELETE;
		$res = $objQuestionBase->updateByPk($questionId, $data);
		if ($res) {
                    //同时问卷网点也删除
                    NetworkQuestion::model()->deleteAll('question_id='.$questionId);
                    //同时删除回答
                    NetworkQuestionAnswer::model()->deleteAll('question_id='.$questionId);
                    //项目问卷数量减一
                    Project::model()->updateCounters(array('question_total' => -1), 'project_id=:project_id', array(':project_id' => $project_id));
                    $this->_ajax(array('status' => 1,'note' => '删除成功'));
		} else {
                    $this->_ajax(array('status' => 0,'note' => '删除失败'));
		}
	}

	/**
	 * 在线添加某问卷下面的网点
	 */
	public function actionAddnetwork() {
		$question_id = $this->post('question_id');
		$up_network_id = $this->get('up_network_id', 0);
		$this->smarty->assign('banklist', NetworkBank::model()->getKv());
		$this->smarty->assign('alllevel', NetWork::networkLevel());
		$this->smarty->assign('up_network_id', $up_network_id);
		$this->smarty->display('question/add_network.tpl');
	}

	/**
	 * 添加
	 */
	public function actionDoAddnetwork() {
		$question_id = (int) $this->post('question_id');
		$data['bank_id'] = (int) $this->post('bank_id');
		$data['network_num'] = $this->post('network_num');
		$data['network_name'] = $this->post('network_name');
		$data['network_username'] = $this->post('network_username');
		$data['network_pwd'] = $this->post('network_pwd');
		$data['level'] = (int) $this->post('level');
		$data['auth_grade'] = (int) $this->post('auth_grade');
		$data['up_network_id'] = (int) $this->post('up_network_id');
		$data['leader'] = $this->post('leader');
		$data['email'] = $this->post('email');
		$data['phone'] = $this->post('phone');
		//根据银行和网点编号，判断编号是否存在
		if (!$networkModel = NetWork::model()->find('bank_id = ' . $data['bank_id'] . ' and network_num="' . $data['network_num'] . '"')) {//更新
			$networkModel = new NetWork();
		}

		$networkModel->network_num = $data['network_num'];
		$networkModel->network_name = $data['network_name'];
		$networkModel->leader = $data['leader'];
		$networkModel->phone = $data['phone'];
		$networkModel->email = $data['email'];
		$networkModel->network_username = $data['network_username'];
		$networkModel->network_pwd = $data['network_pwd'];
		$networkModel->bank_id = $data['bank_id'];
		$networkModel->level = $data['level'];
		$networkModel->auth_grade = $data['auth_grade'];
		$networkModel->up_network_id = $data['up_network_id'];

		$networkModel->create_time = time();
		$networkModel->update_time = time();
		$networkModel->user_id = $this->user_id ? $this->user_id : 0;
		$res = $networkModel->save();

		if ($res) {
			$network_id = $networkModel->network_id;

			$question = QuestionBase::model()->findByPk($question_id)->attributes;

			$networkquestion = new NetworkQuestion();
			$networkquestion->project_id = $question['project_id'];
			$networkquestion->network_id = $network_id;
			$networkquestion->network_name = $data['network_name'];
			$networkquestion->create_time = time();
			$networkquestion->update_time = time();
			$networkquestion->save();
			$this->jump('操作成功', '/webadmin/netquestion/list?question_id=' . $question_id);
		} else {
			$this->jump('操作失败');
		}
	}

	/**
	 * 发布问卷
	 */
	public function actionRelease() {
		$questionId = (int) $this->post('question_id');
                $status = (int)$this->post('status');
		$objQuestionBase = new QuestionBase();
		$data['status'] = $status;
		$res = $objQuestionBase->updateByPk($questionId, $data);
                $info = QuestionBase::model()->findByPk($questionId)->attributes;
		if ($res) {
                    //发布,项目增加问卷数，网点问卷改为正常
                    if ($status == QuestionBase::QUESTION_RELEASE) {
                        Project::model()->updateCounters(array('question_num' => 1), 'project_id=:project_id', array(':project_id' => $info['project_id']));
                        NetworkQuestion::model()->updateAll(array('status' => NetworkQuestion::NETWORK_QUESTION_NORMAL),'question_id=:question_id',array(':question_id' => $questionId));
                    }
                    //草稿,项目减少问卷数，网点问卷改为暂停
                    if ($status == QuestionBase::QUESTION_DRAFT) {
                        Project::model()->updateCounters(array('question_num' => -1), 'project_id=:project_id', array(':project_id' => $info['project_id']));
                        NetworkQuestion::model()->updateAll(array('status' => NetworkQuestion::NETWORK_QUESTION_PAUSE),'question_id=:question_id',array(':question_id' => $questionId));
                    }
                    $this->_ajax(array('status' => 1,'note' => '操作成功'));
		} else {
                    $this->_ajax(array('status' => 0,'note' => '操作失败'));
		}
	}
	/**
	 * 手动设置问卷内容
	 */
	public function actionSet() {
		$template = 'question/set.tpl';
		$p = (int) $this->get('p', 1);
		$typeId = $this->get('tid');
		$questionId = $this->get('qid', 0);

		if ($typeId) {
			$templateEn = QuestionSubject::getQuestionType($typeId);
			if (!$templateEn) {
				$this->jump('无此类型的题型');
			}
			$template = 'question/set_' . $templateEn['title_en'] . '.tpl';
			$this->smarty->assign('templateEn', $templateEn);
		}

		# 获取已经添加的题目
		$questionSubject = new QuestionSubject();
		$criteria = new CDbCriteria();
		$criteria->addCondition('question_id=' . $questionId);

		$count = $questionSubject->count($criteria);
		$criteria->limit = $this->limit;
		$criteria->offset = ($p - 1) * $this->limit;
		$criteria->order = 'subject_id desc';
		$subjects = $questionSubject->findAll($criteria);
		$subjects = $questionSubject->formatSubject($subjects);

		$page = new Page($count, $this->limit);

		$this->smarty->assign('page', $page->style1());
		$this->smarty->assign('subjects', $subjects);
		$this->smarty->assign('fillTextType', QuestionSubject::$fill_text_type);
		$this->smarty->assign('fillDataType', QuestionSubject::$fill_data_type);
		$this->smarty->assign('questionType', QuestionSubject::$question_type);
		$this->smarty->assign('score_display_item', QuestionSubject::$score_display_item);
		$this->smarty->assign('classify', QuestionSubjectClassify::model()->getByQuestion($questionId));  // 获取已经存在的层级结构（即问题归类信息）
		$this->smarty->assign('typeId', $typeId);
		$this->smarty->assign('questionId', $questionId);
		$this->smarty->display($template);
	}

	/**
	 * 添加问卷内容板块
	 */
	public function actionAddClassify() {
		$questionId = $this->post('qid');
		$parent_id = $this->post('parent_id');
		$ctype = $this->post('ctype');
		$name = $this->post('name');
		if (!$questionId || !$name) {
			ajax_fail_exit('参数不完整');
		}
		#入库
		$classifyObj = new QuestionSubjectClassify();
		$classifyObj->question_id = $questionId;
		$classifyObj->classify_name = $name;
		$classifyObj->parent_id = $parent_id;
		$classifyObj->classify_type = $ctype;
		$classifyObj->create_time = time();
		$res = $classifyObj->save();
		if ($res) {
			$classify = $classifyObj->getKv($questionId, $ctype);
			krsort($classify);
			$result = array();
			foreach ($classify as $key => $value) {
				$result[] = array(
					'key' => $key,
					'value' => $value
				);
			}
			ajax_success_exit($result);
		}
		ajax_fail_exit('插入失败，请重试');
	}

	/**
	 * 检查题目编号
	 * @param type $questionNum
	 * @param type $quesionId
	 */
	public function actionCheckQuestionNum() {
		$questionNum = $this->post('question_num');
		$questionId = $this->post('question_id');
		$subject_id = $this->post('subject_id');
		if (!$questionNum || !$questionId) {
			ajax_fail_exit('请填写题目编号或者问卷ID');
		}
		$criteria = new CDbCriteria();
		$criteria->addCondition('question_num="' . $questionNum . '"');
		$criteria->addCondition('question_id=' . $questionId);
		if ($subject_id) {
			$criteria->addNotInCondition('subject_id', array($subject_id));
		}
		$exists = QuestionSubject::model()->find($criteria);

		if ($exists) {
			ajax_fail_exit('该题目编号已经存在');
		}
		ajax_success_exit('题目编号不存在');
	}

	/**
	 * 处理添加或者修改问卷内容
	 */
	public function actionDoSet() {
		$question_id = $this->post('question_id');
		if (!$question_id) {
			ajax_fail_exit('缺少问卷ID');
		}
		// 允许入库的字段名称
		$allowArray = array('subject_id', 'question_id', 'is_basic', 'is_required', 'question_type', 'question_type_sub', 'three_classify_id', 'question_num', 'title', 'text_type', 'content', 'data_type', 'width', 'height', 'is_other', 'keys', 'values', 'standard_score', 'display_items', 'is_relation', 'relation_num');
		$postData = $_POST;
		$setData = array();
		foreach ($postData as $key => $value) {
			if (in_array($key, $allowArray)) {
				$setData[$key] = $value;
			}
			# options的内容
			if ($key == 'keys') {
				foreach ($postData[$key] as $i => $v) {
					$setData['option'][strtoupper($v)] = $postData['values'][$i];
				}
			}
			unset($setData['keys']);
			unset($setData['values']);

			# dispaly_items的内容
			if ($key == 'display_items') {
				$tmp = array();
				foreach ($postData[$key] as $i => $v) {
					$tmp[$v] = QuestionSubject::$score_display_item[$v];
				}
				$setData['display_items'] = $tmp;
			}

			# 是否关联题目不存在时，删除关联题目编号
			if (!isset($setData['is_relation']) || !$setData['is_relation']) {
				unset($setData['relation_num']);
			}
		}

		# 一些附件内容的处理
		$setData['is_required'] = isset($setData['is_required']) ? $setData['is_required'] : 0;
		if (isset($setData['is_other'])) {
			$setData['is_other'] = $setData['is_other'] ? $setData['is_other'] : 0;
		}

		# 三级指标的id处理
		if (isset($setData['three_classify_id'])) {
			$setData['classify_id'] = $setData['three_classify_id'] ? $setData['three_classify_id'] : 0;
			unset($setData['three_classify_id']);
		}
		# 如果是基础信息，classify_id为0
		if ($setData['is_basic']) {
			$setData['classify_id'] = 0;
		}

		$questionSubject = new QuestionSubject();
		$status = $questionSubject->addQuestionSubject($question_id, array($setData));
		if ($status) {
			$return['text'] = "操作成功";
			$return['url'] = $setData['subject_id'] ? '/webadmin/question/set?qid=' . $question_id : false;
			ajax_success_exit($return);
		} else {
			ajax_fail_exit('操作失败');
		}
	}

	/**
	 * 删除问卷题目
	 */
	public function actionSubjectDelete() {
		$subject_id = $this->post('subject_id');
		if (!$subject_id) {
			ajax_fail_exit('请选择要删除的记录');
		}
		$delStatus = QuestionSubject::model()->deleteByPk($subject_id);
		if ($delStatus) {
			ajax_success_exit('删除成功');
		} else {
			ajax_fail_exit('删除失败');
		}
	}
	
	/**
	 * 删除题目分类，各级分类删除时，检查本身是否对应有记录，有，提示用户，先删除下级，否则，直接删除
	 */
	public function actionClassifyDelete(){
		$question_id = $this->post('qid');
		$classify_id = $this->post('classify_id');
		$ctype = $this->post('ctype');
		if (!$question_id || !$classify_id || !$ctype) {
			ajax_fail_exit("请选择分类信息");
		}
		
		
		$returnStr = '';
		$classify_del = false;
		$classifyModel = new QuestionSubjectClassify();
		/**
		 * 判断classify分类，采取对应的措施
		 * 1.一级指标，检查父ID为当前classify_id，且type为2,3的记录
		 * 2.二级指标，检查父ID为当前classify_id，且type为3的记录
		 * 3.三级指标，检查subject表中，classify_id为当前classify_id的记录
		 */
		switch ($ctype) {
			case QuestionSubjectClassify::QUESTION_NORM_ONE:
				$classify = $classifyModel->findAll('parent_id=' . $classify_id . " and classify_type in(" . join(',', array(QuestionSubjectClassify::QUESTION_NORM_TWO, QuestionSubjectClassify::QUESTION_NORM_THREE)) . ")");
				if (!empty($classify)) {
					$returnStr = "当前指标下存在二级指标或者三级指标，请先删除二级指标或者三级指标";
				}else{
					$classify_del = true;
				}
				break;
				
			case QuestionSubjectClassify::QUESTION_NORM_TWO:
				$classify = $classifyModel->findAll('parent_id=' . $classify_id . " and classify_type in(". join(',', array(QuestionSubjectClassify::QUESTION_NORM_THREE)) .")");
				if (!empty($classify)) {
					$returnStr = "当前指标下存在三级指标，请先删除三级指标";
				}else{
					$classify_del = true;
				}
				break;
			case QuestionSubjectClassify::QUESTION_NORM_THREE:
				$classifySubject = QuestionSubject::model()->findAll('question_id=' . $question_id . ' and classify_id=' . $classify_id);
				if (!empty($classifySubject)) {
					$returnStr = "当前指标下存在问卷题目信息，请先删除问卷题目";
				}else{
					$classify_del = true;
				}
				break;

			default:
				break;
		}
		
		# 返回错误信息
		if ($returnStr) {
			ajax_fail_exit($returnStr);
		}
		
		# 通过检测，删除，如果是三级指标，则需要删除subject的信息
		if ($classify_del) {
			$delSta = $classifyModel->deleteAll('classify_id=' . $classify_id . ' and classify_type=' . $ctype);
			if ($delSta) {
				ajax_success_exit("删除成功");
			}else{
				ajax_fail_exit("删除失败，可能的原因：参数传递错误");
			}
		}
		
		ajax_fail_exit("参数错误，请检查");
		
	}

	/**
	 * 编辑问卷内容
	 */
	public function actionSubjectEdit() {
		$typeId = $this->get('tid');
		$questionId = $this->get('qid');
		$subjectId = $this->get('sid');
		if (!$subjectId) {
			$this->jump('请填写题目ID');
		}

		$template = '';
		if ($typeId) {
			$templateEn = QuestionSubject::getQuestionType($typeId);
			if (!$templateEn) {
				$this->jump('无此类型的题型');
			}
			$template = 'question/set_' . $templateEn['title_en'] . '.tpl';
		}

		# 获取题目信息
		$questionSubject = QuestionSubject::model();
		$subjectOne = $questionSubject->findByPk($subjectId)->attributes;
		$subjectOne = $questionSubject->formatSubject(array($subjectOne));
		$tmpOne = array_pop($subjectOne);

		// 获取归类信息
		$norm = QuestionSubjectClassify::model()->getClassifyByThree($tmpOne['classify_id']);
		if ($norm) {
			$subjectOne = array_merge($tmpOne, $norm);
		} else {
			$subjectOne = $tmpOne;
		}

		$this->smarty->assign('fillTextType', QuestionSubject::$fill_text_type);
		$this->smarty->assign('fillDataType', QuestionSubject::$fill_data_type);
		$this->smarty->assign('questionType', QuestionSubject::$question_type);
		$this->smarty->assign('score_display_item', QuestionSubject::$score_display_item);
		$this->smarty->assign('classify', QuestionSubjectClassify::model()->getByQuestion($questionId));  // 获取已经存在的层级结构（即问题归类信息）
		$this->smarty->assign('templateEn', $templateEn);
		$this->smarty->assign('subjectOne', $subjectOne);
		$this->smarty->assign('typeId', $typeId);
		$this->smarty->assign('questionId', $questionId);
		$this->smarty->display($template);
	}

	/**
	 * 导入问卷题目
	 */
	public function actionImport() {
		$questionId = intval($this->get('question_id'));
		$type = intval($this->get('type', 1));
		$this->smarty->assign('question_id', $questionId);
		$this->smarty->assign('type', $type);
		$this->smarty->display('question/import.tpl');
	}

	/**
	 * 处理导入问卷
	 */
	public function actionDoImport() {
		$questionId = $this->post('question_id');

		$upload = new Uploader();
		$config = array(
			'new_name' => 'content_' . $questionId,
			'allow_ext' => 'xls,xlsx',
			'save_path' => dirname(Yii::app()->basePath) . '/assets/question_network/',
			'allow_max_size' => 8000000
		);
		$upload->init($config);

		# 上传验证不通过，提示原因
		if (!$upload->check()) {
			$this->jump($upload->geterror());
		}

		//解析excel数据
		$uploadFilePath = $upload->up();
		$modelSubjectImport = new QuestionSubjectImportModel();

		try {
			// 自定义错误类型，友好提示用户
			ini_set('display_errors', 'Off');
			register_shutdown_function(function() {
				$last_error = error_get_last();
				if ($last_error['type'] === E_ERROR) {
					call_user_func('customError', '');
				}
			});
			
			$this->enablePHPExcel();
			$questionImport = new QuestionExcel();
			$type = explode('.', $uploadFilePath);
			$message = $questionImport->questionContentImport($uploadFilePath, $type[1]);
			
			//处理解析数据(入库，提示等操作)
			$modelSubjectImport->formatExcelData($questionId, $message['msg']);
			$formatError = $modelSubjectImport->getError();
		} catch (Exception $exc) {
			$error[] = $exc->getMessage();
		}
		if (!empty($error)) {
			$this->jump(join(' | ', $error));
		}
		if (!empty($formatError)) {
			$newFormat = array();
			foreach ($formatError as $key => $err) {
				$newFormat[$err['err_no']] = array(
					'err_no' => $err['err_no'],
					'err_msg' => $err['err_msg']
				);
			}

			$this->smarty->assign('backurl', '/webadmin/question/list');
			$this->smarty->assign('error', $newFormat);
			$this->smarty->display('question/import_error.tpl');
			exit;
		}

		# 保存解析数据
		$status = $modelSubjectImport->saveExcelData();

		if ($status) {
			$this->jump('导入成功', '/webadmin/question/list');
		} else {
			$this->jump('导入失败');
		}
	}

	/**
	 * 上传附件
	 * 一个问卷上传zip包
	 * 包括所有下面网点问卷的题目对标附件
	 */
	public function actionAttachment() {
            $questionId = (int)$this->get('question_id');
            $this->smarty->assign('action', 'doAttachment');
            $this->smarty->assign('question_id', $questionId);
            //项目信息，超过大小发邮件
            $question_info = QuestionBase::model()->findByPk($questionId)->attributes;
			$project_info = Project::model()->findByPk($question_info['project_id'])->attributes;
            $this->smarty->assign('project_info',$project_info);
            ///zip包上传处理历史记录    
            $p = $this->get('p', 1);
            $criteria = new CDbCriteria();
            $criteria->addColumnCondition(array('question_id' => $questionId));
            $count = NetworkQuestionZip::model()->count($criteria);
            $criteria->limit = 4;
            $criteria->offset = ($p -1 ) * 4;
            $criteria->order = 'update_time desc';
            $list = NetworkQuestionZip::model()->findAll($criteria);
            
            $page = new Page($count, 4);
            $this->smarty->assign('page', $page->style1());
            $this->smarty->assign('list', $list);

            $this->smarty->display('question/attachment_new.tpl');
	}

	/**
	 * 大文件上传
	 */
	public function actionLarge() {
		$questionId = (int) $this->get('question_id');
		$this->smarty->assign('question_id', $questionId);
		$this->smarty->display('question/large_attachment.tpl');
	}

	/**
	 * 导入问卷回答内容
	 */
	public function actionAnswerImport() {
		$questionId = intval($this->get('question_id'));
		$type = intval($this->get('type', 1));
		$this->smarty->assign('question_id', $questionId);
		$this->smarty->assign('type', $type);
		$this->smarty->display('question/answer_import.tpl');
	}

	/**
	 * 处理回答导入
	 */
	public function actionDoAnswerImport() {
		$questionId = $this->post('question_id');

		$upload = new Uploader();
		$config = array(
			'new_name' => 'question_answer_' . $questionId,
			'allow_ext' => 'xls,xlsx',
			'save_path' => dirname(Yii::app()->basePath) . '/assets/question_network/',
			'allow_max_size' => 8000000
		);
		$upload->init($config);

		# 上传验证不通过，提示原因
		if (!$upload->check()) {
			$this->jump($upload->geterror());
		}

		//解析excel数据
		$uploadFilePath = $upload->up();
		$modelAnswerImport = new QuestionAnswerImportModel();

		try {
			// 自定义错误类型，友好提示用户
			ini_set('display_errors', 'Off');
			register_shutdown_function(function() {
				$last_error = error_get_last();
				if ($last_error['type'] === E_ERROR) {
					call_user_func('customError', '');
				}
			});

			$this->enablePHPExcel();
			$questionImport = new QuestionExcel();
			$type = explode('.', $uploadFilePath);
			$message = $questionImport->questionAnswerImport($uploadFilePath, $type[1]);
			
			//处理解析数据(入库，提示等操作)
			$modelAnswerImport->formatExcelData($questionId, $message['msg']);
			$formatError = $modelAnswerImport->getError();
			$new = $formatError;
			if ($formatError) {
				$tmp = array();
				foreach ($formatError as $key => $data) {
					$tmp[$data['err_msg']][] = $data['err_no'];
				}
				$new = array();
				foreach ($tmp as $key => $data) {
					$new[] = array(
						'err_no' => join(',', array_unique($data)),
						'err_msg' => $key
					);
				}
			}
		} catch (Exception $exc) {
			$error[] = $exc->getMessage();
		}
		if (!empty($error)) {
			$this->jump(join(' | ', $error));
		}
		if (!empty($formatError)) {
			$this->smarty->assign('question_id', $questionId);
			$this->smarty->assign('backurl', '/webadmin/question/answerImport?question_id=' . $questionId);
			$this->smarty->assign('error', $new);
			$this->smarty->display('question/import_error.tpl');
			exit;
		}

		# 保存解析数据
		$status = $modelAnswerImport->saveExcelData();
		if ($status) {
			$this->jump('导入成功', '/webadmin/question/list');
		} else {
			$this->jump('导入失败');
		}
	}
	
	/**
	 * 对标回答导入
	 */
	public function actionBenchmarkImport(){
		$questionId = intval($this->get('question_id'));
		$type = intval($this->get('type', 1));
		$this->smarty->assign('question_id', $questionId);
		$this->smarty->display('question/benchmark_import.tpl');
	}
	
	/**
	 * 处理对标回答导入
	 */
	public function actionDoBenchmarkImport() {
		$questionId = $this->post('question_id');

		$upload = new Uploader();
		$config = array(
			'new_name' => 'question_benchmark_' . $questionId,
			'allow_ext' => 'xls,xlsx',
			'save_path' => dirname(Yii::app()->basePath) . '/assets/question_network/',
			'allow_max_size' => 10000000
		);
		$upload->init($config);

		# 上传验证不通过，提示原因
		if (!$upload->check()) {
			$this->jump($upload->geterror());
		}

		//解析excel数据
		$uploadFilePath = $upload->up();
		$modelBenchmarkImport = new QuestionBenchmarkImportModel();

		try {
			// 自定义错误类型，友好提示用户
			ini_set('display_errors', 'Off');
			register_shutdown_function(function() {
				$last_error = error_get_last();
				if ($last_error['type'] === E_ERROR) {
					call_user_func('customError', '');
				}
			});

			$this->enablePHPExcel();
			$questionImport = new QuestionExcel();
			$type = explode('.', $uploadFilePath);
			$message = $questionImport->questionBenchmarkImport($uploadFilePath, $type[1]);
			
			//处理解析数据(入库，提示等操作)
			$modelBenchmarkImport->formatExcelData($questionId, $message['msg']);
			$formatError = $modelBenchmarkImport->getError();
			$new = $formatError;
			if ($formatError) {
				$tmp = array();
				foreach ($formatError as $key => $data) {
					$tmp[$data['err_msg']][] = $data['err_no'];
				}
				$new = array();
				foreach ($tmp as $key => $data) {
					$new[] = array(
						'err_no' => join(',', array_unique($data)),
						'err_msg' => $key
					);
				}
			}
		} catch (Exception $exc) {
			$error[] = $exc->getMessage();
		}
		if (!empty($error)) {
			$this->jump(join(' | ', $error));
		}
		if (!empty($formatError)) {
			$this->smarty->assign('question_id', $questionId);
			$this->smarty->assign('backurl', '/webadmin/question/benchmarkImport?question_id=' . $questionId);
			$this->smarty->assign('error', $new);
			$this->smarty->display('question/import_error.tpl');
			exit;
		}

		# 保存解析数据
		$status = $modelBenchmarkImport->saveExcelData();
		if ($status) {
			$this->jump('导入成功', '/webadmin/question/list');
		} else {
			$this->jump('导入失败');
		}
	}

	/**
	 * 预览问卷
	 */
	public function actionView() {
		$question_id = (int) $this->get('question_id');
        $question = new QuestionBase();
        $question_info = $question->findByPk($question_id)->attributes;
        //问卷基本扩展基本信息，从题目里面出
        $questionsubject = new QuestionSubject();
        $basic_list = $questionsubject->getBasic($question_id);
        
        //问卷题目
        $questionsubject = new QuestionSubject();
        $subject_list = $questionsubject->getByGroupClassify($question_id);
        //问卷的区块
        $subjectclassify = new QuestionSubjectClassify();
        $classify_list = $subjectclassify->getByQuestion($question_id);
        //print_r($classify_list);exit;
        //问题的选项
        $questionoption = new QuestionOption();
        $option = $questionoption->getByQuestion($question_id);

        $this->smarty->assign('question_info', $question_info);
        $this->smarty->assign('subject_list', $subject_list);
        $this->smarty->assign('classify_list', $classify_list);
        $this->smarty->assign('option_list', $option);
        $this->smarty->assign('basic_list', $basic_list);
        $this->smarty->display('question/view.tpl');
    }
	
	//问卷内容导入模板下载
	public function actionTemplateDown() {
		header("Content-type: application/octet-stream");
		header("Accept-Ranges: bytes");
                header("Content-Type:application/force-download");
                header("Content-Transfer-Encoding:binary");
                header('Content-Type: application/vnd.ms-excel; charset=utf-8'); 
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header("Content-Disposition:attachment;filename=".urlencode('问卷内容导入模板').".xlsx");
		readfile(dirname(Yii::app()->BasePath) . '/assets/import_template/question_content_import.xlsx');
		exit;
	}

	//问卷对标导入模板下载
	public function actionTemplateAnswerDown() {
		$question_id = $this->get('question_id');
		$subjectTable = QuestionSubject::model()->getListByBase($question_id);
        if ($question_id == 875 || $question_id == 870) {
            //print_r($subjectTable);exit;
        }
		if (!$subjectTable) {
			$this->jump('当前问卷暂时没有问卷内容数据，模板不能生成');
		}
		$this->enablePHPExcel();
		$networkExcel = new NetworkExcel();
		$networkExcel->quesionAnswerTemplate($question_id, $subjectTable, '问卷回答导入模板_问卷ID' . $question_id);
	}
	
	//导出申诉模板下载
	public function actionTemplateBenchmarkDown() {
		$question_id = $this->get('question_id');
		
		//基础数据
		$subjectIds = array();
		$nqIds = array();
		$subjectTable = QuestionSubject::model()->getListByBase($question_id);
		foreach ($subjectTable as $subNum => $v) {
			$subjectIds[$v['subject_id']] = $v['subject_id'];
			$subjectTable[$v['subject_id']] = $v;
		}
		$questionDetail = QuestionBase::model()->find('question_id=' . $question_id);
		$project_id = $questionDetail->project_id;
		$questionNetwork = NetworkQuestion::model()->getQuestionNetwork($question_id, $project_id);
		foreach ($questionNetwork as $netNum => $val) {
			$nqIds[$val['nq_id']] = $val['nq_id'];
			$questionNetwork[$val['nq_id']] = $val;
		}
		
		// 1.查出还分数据
		$benchmark = array();
		foreach ($nqIds as $nq_id) {
			$tmpBench = QuestionBenchmark::model()->getNqList($nq_id);
			if ($tmpBench) {
				$benchmark[$nq_id] = $tmpBench;
			}
		}
		if (!$benchmark) {
			$this->jump('当前问卷暂时没有还分申请数据，模板不能生成');
		}
		
		// 2.组建还分数据
		$excelData = array();
		$someItems = array();  # 保存当前导出时候的总行，分行，支行信息
		foreach ($benchmark as $qNqId => $val) {
			foreach ($val as $subId => $data) {
				
				// 获取回答数据
				$answer = NetworkQuestionAnswer::model()->getBySubject($qNqId, $subId);
				
				// 分别对应
				$uniKey = $qNqId . '_' . $subId;
				$excelData[$uniKey] = array(
					'network_name' => $questionNetwork[$qNqId]['network_name'],
					'network_num' => $questionNetwork[$qNqId]['network_num'],
					'question_num' => $subjectTable[$subId]['question_num'],
					'standard_score' => $subjectTable[$subId]['standard_score'],
					'answer_score' => $answer['answer_score'],
					'answer_desc' => $answer['answer_desc'],
				);
				
				# 总行，分行，支行取值
				foreach ($data as $chrK => $chrD) {
					// 排除不是数组的选项
					if (!is_array($chrD)) {
						continue;
					}
					// 如果是自己的，表示是申请
					if ($chrD['is_self']) {
						$excelData[$uniKey]['suggestion'] = $chrD['suggestion'];
						continue;
					}
					# 判断总行，分行，支行
					switch ($chrD['level']) {
						case 1:
							$excelData[$uniKey]['level_one_last_time'] = $chrD['last_time'];
							$excelData[$uniKey]['level_one_suggestion'] = $chrD['suggestion'];
							break;
						
						case 2:
							$excelData[$uniKey]['level_two_suggestion'] = $chrD['suggestion'];
							$excelData[$uniKey]['level_two_isreturn'] = $chrD['isreturn'] ? "是" : "否";
							$excelData[$uniKey]['level_two_dissent'] = $chrD['dissent'];
							break;
						case 3:
							$excelData[$uniKey]['level_three_suggestion'] = $chrD['suggestion'];
							$excelData[$uniKey]['level_three_isreturn'] = $chrD['isreturn'] ? "是" : "否";
							$excelData[$uniKey]['level_three_dissent'] = $chrD['dissent'];
							break;
						default:
							break;
					}
				}
			}
		}
		
		// 3.查出赛诺处理意见
		$tmp = $excelData;
		foreach ($tmp as $nq_sub_id => $value) {
			list($nq_id, $subId) = explode('_', $nq_sub_id);
			$benchManage = QuestionBenchmarkManage::model()->findAllByAttributes(array(
				'nq_id' => $nq_id,
				'subject_id' => $subId,
			));
			if (!empty($benchManage)) {
				$benchManage = array_pop($benchManage);
				$benchManageArr = $benchManage->attributes;
				
				# 赛诺处理的值
				$someItems['sino'] = true;
				$excelData[$nq_sub_id]['sino_handle_suggestion'] = $benchManageArr['suggestion'];
				$excelData[$nq_sub_id]['sino_handle_isreturn'] = is_numeric($benchManageArr['isreturn']) ? "是" : "否";
				$excelData[$nq_sub_id]['sino_handle_isreturnvalue'] = is_numeric($benchManageArr['isreturn']) ? $benchManageArr['isreturn'] : "";
			}
			
			# 后台导出时间
			$excelData[$nq_sub_id]['export_time'] = date("Y-m-d H:i:s");
			
		}
		
		# 判断当前问卷存在哪些网点级别
		$allLevels = NetworkQuestion::model()->getAllLevelNetwork($question_id, $project_id);
		if ($allLevels) {
			foreach ($allLevels as $level => $boolVal) {
				$someItems[$level] = $boolVal;
			}
		}
		
		$excelData['some_items'] = $someItems;
		$this->enablePHPExcel();
		$networkExcel = new NetworkExcel();
		$networkExcel->quesionBenchmarkTemplate($question_id, $excelData, '问卷申诉导出模板_问卷ID' . $question_id);
	}

        /**
         * 访问zip报解析情况
         */
        public function actionZip()
        {
            $p = $this->get('p', 1);
            $criteria = new CDbCriteria();
            $criteria->limit = $this->limit;
            $criteria->offset = ($p -1 ) * $this->limit;
            $criteria->order = 'update_time desc';
            $list = NetworkQuestionZip::model()->findAll($criteria);
            if ($list) {
                //查找问卷
                foreach ($list as $key => $val) {
                    $question_id = $val['question_id'];
                    $question_info = QuestionBase::model()->findByPk($question_id)->attributes;
                    $list[$key]['question_name'] = $question_info['question_name'];
                    $list[$key]['identifier'] = $question_info['identifier'];
                }
            }
            $count = NetworkQuestionZip::model()->count();
            $page = new Page($count, $this->limit);
            $this->smarty->assign('page', $page->style1());
            $this->smarty->assign('list', $list);
            $this->smarty->display('question/zip.tpl');
        }
        /**
         * 删除附件
         */
        public function actionDelZip()
        {
            $nqz_id = $this->post('nqz_id');
            if (NetworkQuestionZip::model()->deleteByPk($nqz_id)) {
                    ajax_success_exit("操作成功");
            }else{
                    ajax_fail_exit("操作失败");
            }
        }
    /**
     * 是否显示得分
     */
    public function actionScore()
    {
        $question_id = $this->get('question_id');
        $show_score = $this->get('show_score');
        if (QuestionBase::model()->updateByPk($question_id, array('show_score' => $show_score))) {
                ajax_success_exit("操作成功");
        }else{
                ajax_fail_exit("操作失败");
        }
    }
}
